要如何串接任意的API格式到遊戲中?
包含OpenAI, Google, 其他HTTP API
1. 了解要串接的的API接收和回傳的Json格式
API接收的JSON格式:
{
"id": 1
}
API回傳的JSON格式:
{
"id": 1,
"name": "John Doe",
"email": "johndoe@example.com",
"age": 30
}
2. 使用JsonToC#
上面的案例比較簡單
但如果遇到比較複雜的格式
我們可以直接使用現成的工具
把Json格式轉換成C#的Class
3. 使用Unity Web Request去呼叫和提取API
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using Newtonsoft.Json;
public class APIClient : MonoBehaviour
{
private string apiUrl = "https://api.example.com/data";
// Action for handling the processed data
public System.Action<PlayerData> OnDataReceived;
// POST request to send JSON data
public IEnumerator PostRequest(int playerId)
{
PlayerRequestData requestData = new PlayerRequestData { Id = playerId };
string json = JsonConvert.SerializeObject(requestData);
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(jsonToSend);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
string jsonResponse = request.downloadHandler.text;
ProcessResponse(jsonResponse);
}
else
{
Debug.LogError("Error: " + request.error);
}
}
private void ProcessResponse(string jsonResponse)
{
// Process and map the JSON response to the PlayerData class
PlayerData playerData = JsonConvert.DeserializeObject<PlayerData>(jsonResponse);
// Invoke the action if it's not null
OnDataReceived?.Invoke(playerData);
}
}
// Class to represent the request data
public class PlayerRequestData
{
public int Id { get; set; }
}
// Class to represent the response data
public class PlayerData
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
我們在這一步可以把回傳的json轉成可以使用的Class
private void ProcessResponse(string jsonResponse)
{
// 將JSON響應轉換為PlayerData對象
PlayerData player = JsonConvert.DeserializeObject<PlayerData>(jsonResponse);
// 處理並使用轉換後的數據
Debug.Log("Player Name: " + player.Name);
Debug.Log("Player Email: " + player.Email);
Debug.Log("Player Age: " + player.Age);
OnDataReceived?.Invoke(playerData);
}
using UnityEngine;
public class GameManager : MonoBehaviour
{
// 引用APIClient
public APIClient apiClient;
void Start()
{
// 確保apiClient已經在Inspector中賦值
if (apiClient != null)
{
// 設置處理API返回數據的回調
apiClient.OnDataReceived = HandleAPIResponse;
// 發起POST請求並傳入玩家ID
StartCoroutine(apiClient.PostRequest(1));
}
else
{
Debug.LogError("APIClient is not assigned in the Inspector!");
}
}
// 回調函數來處理API返回的數據
private void HandleAPIResponse(PlayerData playerData)
{
if (playerData != null)
{
// 在這裡處理API返回的數據,例如更新UI或遊戲邏輯
Debug.Log("Player Name: " + playerData.Name);
Debug.Log("Player Email: " + playerData.Email);
Debug.Log("Player Age: " + playerData.Age);
}
else
{
Debug.LogError("Failed to receive player data.");
}
}
}